package br.com.mural.android.webservice;

import java.util.ArrayList;
import java.util.List;

import br.com.mural.android.entidades.Turma;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;

public class TurmaRest {
	private String URL_WS = WebServiceMural.URL_WS + "turma/";

	public Turma getTurma(int id) throws Exception {

		String[] resposta = new WebServiceMural().get(URL_WS + id);

		if (resposta[0].equals("200")) {
			Gson gson = new Gson();
			Turma turma = gson.fromJson(resposta[1], Turma.class);
			return turma;
		} else {
			throw new Exception(resposta[1]);
		}
	}

	public List<Turma> getListaTurma() throws Exception {

		String[] resposta = new WebServiceMural().get(URL_WS + "allGSON");

		if (resposta[0].equals("200")) {
			Gson gson = new Gson();
			ArrayList<Turma> listaTurma = new ArrayList<Turma>();
			JsonParser parser = new JsonParser();
			JsonArray array = parser.parse(resposta[1]).getAsJsonArray();

			for (int i = 0; i < array.size(); i++) {
				listaTurma.add(gson.fromJson(array.get(i), Turma.class));
			}
			return listaTurma;
		} else {
			throw new Exception(resposta[1]);
		}
	}
	
	public List<Turma> getListaTurmaByUsuario(int id) throws Exception {

		String[] resposta = new WebServiceMural().get(URL_WS + "allByUsuario/"+id);

		if (resposta[0].equals("200")) {
			Gson gson = new Gson();
			ArrayList<Turma> listaTurma = new ArrayList<Turma>();
			JsonParser parser = new JsonParser();
			JsonArray array = parser.parse(resposta[1]).getAsJsonArray();

			for (int i = 0; i < array.size(); i++) {
				listaTurma.add(gson.fromJson(array.get(i), Turma.class));
			}
			return listaTurma;
		} else {
			throw new Exception(resposta[1]);
		}
	}

	public String inserirTurma(Turma turma) throws Exception {

		Gson gson = new Gson();
		String turmaJSON = gson.toJson(turma);
		System.out.println("Turma JSON: " + turmaJSON);
		String[] resposta = new WebServiceMural().post(URL_WS + "inserir", turmaJSON);

		if (resposta[0].equals("200")) {
			return resposta[1];
		} else {
			throw new Exception(resposta[1]);
		}
	}

	public String deletarTurma(int id) {
		String[] resposta = new WebServiceMural().get(URL_WS + "delete/" + id);
		return resposta[1];
	}
}
